/**
 * @description  : 日期时间选择组件：以输入框方式调用
 * @descriptionDetail : 日期时间选择组件：以输入框方式调用
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2022-10-03 17:09:36
 */
<template>
  <view style="width: 100%;">
    <u-input
      :border="border"
      type="select"
      :placeholder="$attrs.placeholder || '请输入'"
      v-model="dataVal"
      v-bind="$attrs"
      @click="show = !readOnly"
      :select-open="show"
    ></u-input>
    <u-picker mode="time" v-model="show" :params="params" :safe-area-inset-bottom="true" @confirm="handleConfirm"></u-picker>
  </view>
</template>
<script>
import Emitter from '@/uview-ui/libs/util/emitter.js';
export default {
  mixins: [Emitter],
  props: {
    value: {
      type: String | Number,
      default: ''
    },
    mask: {   // 是否显示遮罩层
      type: Boolean,
      default: false
    },
    format: { // 日期格式
      type: String,
      default: 'yyyy-MM-dd'
    },
    readOnly: { // 只读
     type: Boolean,
      default: false
    }
  },
  data() {
    let df = this.format;
    return {
      dataVal: this.value,
      border: false,
      show: false,
      dateFormat: this.format,
      params: {
        year: df.includes("yyyy"),
        month: df.includes("MM"),
        day: df.includes("dd"),
        hour: df.includes("HH"),
        minute: df.includes("mm"),
        second: df.includes("ss")
			}
    }
  },
  watch: {
    format: {
      immediate: true,
      handler(v) {
        this.dateFormat = v;
        let df = v;
        this.params = {
          year: df.includes("yyyy"),
          month: df.includes("MM"),
          day: df.includes("dd"),
          hour: df.includes("HH"),
          minute: df.includes("mm"),
          second: df.includes("ss")
        }
      }
    },
    value: {
       immediate: true,
      handler(v) {
        this.dataVal=v;
      }
    }
  },
  methods: {
    handleConfirm(arg) {
      this.dataVal = this.timeFormat(arg, this.dateFormat);
      this.$emit("input", this.dataVal);
      // 将当前的值发送到 u-form-item 进行校验
			this.dispatch('u-form-item', 'on-form-change', this.dataVal);
      this.show = false;
    },
    timeFormat(arg, fmt) {
      let ret;
      const opt = {
        "yyyy": arg.year,        // 年
        "MM": arg.month,     // 月
        "dd": arg.day,            // 日
        "HH": arg.hour,           // 时
        "mm": arg.minute,         // 分
        "ss": arg.second,          // 秒
      };
      for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
          fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")));
        }
      }
      return fmt;
    }
  },
}
</script>